#include <cmd/common.h>
#include "rabbitmq.h"

std::shared_ptr<rabbitmqplus> rabbitmqplus::_inst;

rabbitmqplus::rabbitmqplus(){
    try{
        std::string mq_host = settings.get<std::string>("mq.host", "192.168.5.171");
        settings.put("mq.host",mq_host);
        std::string mq_user = settings.get<std::string>("mq.user", "test");
        settings.put("mq.user",mq_user);
        std::string mq_passwd = settings.get<std::string>("mq.passwd", "test");
        settings.put("mq.passwd",mq_passwd);
        int mq_port = settings.get<int>("mq.port", 5672);
        settings.put("mq.port",mq_port);
        amqp=std::make_shared<AMQP>(mq_user+":"+mq_passwd+"@"+mq_host+":"+std::to_string(mq_port));
        ev = amqp->createExchange("topic_vibration_feature_data");
        ev->Declare("topic_vibration_feature_data", "fanout");
        qe = amqp->createQueue("topic_vibration_feature_data");
		qe->Declare();
		qe->Bind( "topic_vibration_feature_data", "");

        er = amqp->createExchange("topic_record_feature_data");
        er->Declare("topic_record_feature_data", "fanout");
        qr = amqp->createQueue("topic_record_feature_data");
		qr->Declare();
		qr->Bind( "topic_record_feature_data", "");
    }catch(...){
        BOOST_LOG_TRIVIAL(error)<<"rabbitmq connect fail.";
    }
}

bool rabbitmqplus::publish(std::string topic,std::string msg){
    try{
        if(ev!=nullptr&&topic=="topic_vibration_feature_data"){
            std::lock_guard<std::mutex> lock(mtx);
            ev->Publish(msg,"topic_vibration_feature_data");
        }else if(er!=nullptr&&topic=="topic_record_feature_data"){
            std::lock_guard<std::mutex> lock(mtx);
            er->Publish(msg,"topic_record_feature_data"); 
        }else{
            if(ev!=nullptr||er!=nullptr){
                BOOST_LOG_TRIVIAL(warning)<<"invalid topic";
            }
        }
    }catch(...){
        BOOST_LOG_TRIVIAL(warning)<<"rabbitmq publish fail.";
    }
    return true;
}